package com.sv.jm.baselibrary.http;

import android.content.Context;

import com.sv.jm.baselibrary.Coustom.NetWorkException;
import com.sv.jm.baselibrary.R;
import com.sv.jm.baselibrary.utils.GsonHelper;
import com.sv.jm.baselibrary.utils.NetWorkHelper;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Dispatcher;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 胡金辉 on 2017/5/23.
 */

public class RetrofitHelper {
    private long MAX_TIME_OUT = 5 * 1000;
    private int MAX_RETRY_REQUEST = 3;
    private static RetrofitHelper instance = null;

    public static RetrofitHelper getInstance(Context ct) throws NetWorkException {
        if (null == instance)
            synchronized (RetrofitHelper.class) {
                instance = new RetrofitHelper();
            }
        if (!NetWorkHelper.isNetworkAvailable(ct))
            throw new NetWorkException(ct.getString(R.string.net_error));
        return instance;
    }


    public Retrofit getRetrofit(String baseUrl, Map<String, String> header) {
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(GsonHelper.getInstance().getGson()))
                .client(getOkHttp(header))
                .build();
        return retrofit;
    }

    private OkHttpClient getOkHttp(Map<String, String> header) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(MAX_RETRY_REQUEST);

        builder.dispatcher(dispatcher)
                .addInterceptor(new HeaderInterceptor(header))//添加header拦截器
                .retryOnConnectionFailure(true)
                .connectTimeout(MAX_TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(MAX_TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(MAX_TIME_OUT, TimeUnit.MILLISECONDS);
        return builder.build();
    }

    /**
     * header拦截器   从新设置header相关值
     */
    class HeaderInterceptor implements Interceptor {
        Map<String, String> header;

        public HeaderInterceptor(Map<String, String> header) {
            this.header = header;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();
            if (header != null && !header.isEmpty()) {
                for (String key : header.keySet()) {
                    builder.removeHeader(key).header(key, header.get(key));
                }
            }
            return chain.proceed(builder.build());
        }
    }

    private RetrofitHelper() {
    }

}
